var webpack = require('webpack');
const path = require('path'); // 导入路径包
const os = require('os');
var ExtractTextPlugin = require("extract-text-webpack-plugin");  //css单独打包
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");

var HappyPack = require('happypack');
var happyThreadPool = HappyPack.ThreadPool({size: os.cpus().length});//缓存常用模块
var HtmlWebpackPlugin = require('html-webpack-plugin');//html模板生成

var isProduction = function () {
  return process.env.NODE_ENV === 'production';
};
module.exports = {
  entry: {
    main: './src/entry.js', //唯一入口文件
    vendor: ['react']
  },
  output: {
    path: './build', //打包后的文件存放的地方
    filename: isProduction() ? '[name].[hash:8].min.js' : 'main.js', //打包后输出文件的文件名——加缓存方式1
    // filename: '[name]-[chunkhash:6].js', //打包后输出文件的文件名——加缓存方式2
    publicPath: isProduction() ? 'http://jieyan.xyitech.com/static/' : 'http://localhost:8888/build/'//打包上线地址
    // publicPath: isProduction() ? 'http://192.168.31.157:81/' : 'http://localhost:8888/build/'
    // publicPath: isProduction() ? 'http://192.168.1.29:81/' : 'http://localhost:8888/build/'
    // publicPath: 'http://localhost:8888/build/'  //启动本地服务后的根目录
  },

  module: {
    loaders: [
      // {test: /\.js$/, loader: "jsx!babel", include: /src/},
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style", "css!postcss")},
      {test: /\.scss$/, loader: ExtractTextPlugin.extract("style", "css!postcss!sass")},
      {test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192000&name=images/[hash:8].[name].[ext]'},//小于800kb转base64位处理
      {test: /\.html$/, loader: 'html-withimg-loader'}
    ]
  },

  babel: {
    presets: ['es2015', 'stage-0', 'react'],
    plugins: ['transform-runtime', ['import', {
      libraryName: 'antd',
      style: 'css'
    }]]
  },

  postcss: [
    require('autoprefixer')    //调用autoprefixer插件,css3自动补全
  ],

  plugins: [
    new ExtractTextPlugin(isProduction() ? '[name].[hash:8].min.css' : 'main.css'),
    new CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.js'
    })
  ]

}
// 判断开发环境还是生产环境,添加uglify等插件
if (isProduction()) {

  module.exports.module.loaders = (module.exports.module.loaders || [])
    .concat([
      {test: /\.js$/, loader: "jsx!babel", include: /src/}
    ])

  module.exports.plugins = (module.exports.plugins || [])
    .concat([
      new HtmlWebpackPlugin({
        filename: './index.html',    //生成的html存放路径，相对于 path
        template: 'src/views/index.html',    //html模板路径
        inject: true,    //允许插件修改哪些内容，true/'head'/'body'/false,
        chunks: ['vendor', 'main'],//加载指定模块中的文件，否则页面会加载所有文件，注意vender和main先后顺序，公共文件必须在自己引用的js文件上面，否则会报'webpackJsonp is not defined'
        hash: false,    //为静态资源生成hash值
        minify: {    //压缩HTML文件
          removeComments: false,    //移除HTML中的注释
          collapseWhitespace: false    //删除空白符与换行符
        }
      }),
      new webpack.DefinePlugin({
        __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
      }),
      new webpack.optimize.UglifyJsPlugin({//webpack自带js压缩插件，css也会被压缩
        compress: {warnings: false}
      }),
      new webpack.optimize.OccurenceOrderPlugin(),
    ]);
} else {//开发环境开启热更新和source-map
  module.exports.module.loaders = (module.exports.module.loaders || [])
    .concat([
      {test: /\.js$/, loader: 'happypack/loader?id=happybabel', include: /src/}//开发环境，用happypack解析babel，这样不用每次热更新都打包node_modules中常用模块，节约打包时间，大大提高开发效率//
    ])

  module.exports.devtool = 'eval-source-map';//只能在开发环境中使用，会使main.js和vendor.js增大好几倍，比如该例子，main.js从最初的1.6M增大到11.3M，vendor.js从143kb增大到364kb，若是打包到线上环境，真的心中一万只~~~~
  module.exports.devServer = {
    // contentBase: './src/views'  //本地服务器所加载的页面所在的目录
    port: 8888,
    colors: true,  //终端中输出结果为彩色
    historyApiFallback: true,  //不跳转
    inline: true  //实时刷新
  };

  module.exports.plugins = (module.exports.plugins || [])
    .concat([
      new HappyPack({//建议只在开发环境中使用
        id: 'happybabel',
        // loaders: ['babel-loader'],
        loaders: [{
          path: 'babel',
          query: {
            cacheDirectory: '.webpack_cache',
            presets: ['es2015', 'stage-0', 'react'],
            plugins: ['transform-runtime', ['import', {
              libraryName: 'antd',
              style: 'css'
            }]]
          }
        }],
        threadPool: happyThreadPool,
        cache: true,
        verbose: true
      }),
    ]);
}
